package com.xhcl.web.controller.system;

import java.io.File;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFooter;
import org.apache.poi.hssf.usermodel.HSSFPrintSetup;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.xhcl.common.annotation.Log;
import com.xhcl.common.config.SysConfig;
import com.xhcl.common.core.controller.BaseController;
import com.xhcl.common.core.domain.AjaxResult;
import com.xhcl.common.core.page.MulTableDataInfo;
import com.xhcl.common.enums.BusinessType;
import com.xhcl.common.utils.POIUtil;
import com.xhcl.common.utils.file.FileUtils;
import com.xhcl.common.utils.uuid.IdUtils;
import com.xhcl.framework.uitls.poi.ExcelUtil;
import com.xhcl.system.domain.TSrhsAccountTemp;
import com.xhcl.system.domain.TSrhsDwcx;
import com.xhcl.system.model.ChangeHorizontal;
import com.xhcl.system.service.ITSrhsAccountTempService;
import com.xhcl.system.service.ITSrhsDwcxService;
import com.xhcl.system.service.ITSrhsHsxtcsService;

@Controller
@RequestMapping({ "/system/dwcx" })
public class TSrhsDwcxController extends BaseController
{
    private String prefix;
    @Autowired
    private ITSrhsAccountTempService tSrhsAccountTempService;
    @Autowired
    private ITSrhsDwcxService tSrhsDwcxService;
    @Autowired
    private ITSrhsHsxtcsService tSrhsHsxtcsService;
    
    public TSrhsDwcxController() {
        this.prefix = "system/dwcx";
    }
    
    @RequiresPermissions({ "system:dwcx:view" })
    @GetMapping
    public String dwcx(final ModelMap mmap) {
        final String year = this.tSrhsHsxtcsService.getHsxtcsnr("year");
        final String term = this.tSrhsHsxtcsService.getHsxtcsnr("term");
        final List<String> ndlist = new ArrayList<String>();
        for (int i = 0; i < 5; ++i) {
            ndlist.add(String.valueOf(Integer.parseInt(year) - i));
        }
        mmap.put("ndlist", ndlist);
        mmap.put("year", year);
        final List<String> yflist = new ArrayList<String>();
        for (int j = 1; j <= 12; ++j) {
            yflist.add(String.valueOf(j));
        }
        mmap.put("yflist", yflist);
        mmap.put("term", term);
        final List<TSrhsDwcx> list = (List<TSrhsDwcx>)this.tSrhsDwcxService.selectTSrhsDwcxforZbhList((TSrhsDwcx)null);
        mmap.put("zbh", list);
        return this.prefix + "/dwcx";
    }
    
    @RequiresPermissions({ "system:dwcx:list" })
    @PostMapping({ "/list" })
    @ResponseBody
    public MulTableDataInfo list(final TSrhsAccountTemp tSrhsAccountTemp) {
        int iszero = 0;
        if (tSrhsAccountTemp.getParams().get("iszero") != null && tSrhsAccountTemp.getParams().get("iszero").equals("on")) {
            iszero = 1;
        }
        final Map<String, Object> map = new HashMap<String, Object>();
        map.put("zbh", tSrhsAccountTemp.getParams().get("zbh"));
        map.put("nd", tSrhsAccountTemp.getParams().get("nd"));
        map.put("yf", tSrhsAccountTemp.getParams().get("yf"));
        map.put("begindw", tSrhsAccountTemp.getParams().get("sdwbm"));
        map.put("enddw", tSrhsAccountTemp.getParams().get("edwbm"));
        map.put("iszero", iszero);
        String zbh=(String) Optional.ofNullable(tSrhsAccountTemp.getParams().get("zbh")).orElse("") ; 
        List<TSrhsDwcx> zbhList=tSrhsAccountTempService.selectTSrhsDwcxList(zbh);
        final List<ChangeHorizontal> list = this.tSrhsAccountTempService.callDwcx(map);
        return getMulDataTable(list,zbhList);
    }
    
    
    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    protected MulTableDataInfo getMulDataTable(List<?> list,List<?> sublist)
    {
    	MulTableDataInfo rspData = new MulTableDataInfo();
        rspData.setCode(0);
        rspData.setRows(list);
        rspData.setSubrows(sublist);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }
    
    @RequiresPermissions({ "system:dwcx:export" })
    @Log(title = "导出结果", businessType = BusinessType.EXPORT)
    @PostMapping({ "/export" })
    @ResponseBody
    public AjaxResult export(final TSrhsAccountTemp tSrhsAccountTemp,HttpServletResponse response) {

    	AjaxResult ajax = AjaxResult.success();
    	 int iszero = 0;
         if (tSrhsAccountTemp.getParams().get("iszero") != null && tSrhsAccountTemp.getParams().get("iszero").equals("on")) {
             iszero = 1;
         }
         final Map<String, Object> map = new HashMap<String, Object>();
         map.put("zbh", tSrhsAccountTemp.getParams().get("zbh"));
         map.put("nd", tSrhsAccountTemp.getParams().get("nd"));
         map.put("yf", tSrhsAccountTemp.getParams().get("yf"));
         map.put("begindw", tSrhsAccountTemp.getParams().get("sdwbm"));
         map.put("enddw", tSrhsAccountTemp.getParams().get("edwbm"));
         map.put("iszero", iszero);
         String zbh=(String) Optional.ofNullable(tSrhsAccountTemp.getParams().get("zbh")).orElse("") ; 
         List<TSrhsDwcx> zbhList=tSrhsAccountTempService.selectTSrhsDwcxList(zbh);
         final List<ChangeHorizontal> list = this.tSrhsAccountTempService.callDwcx(map); 
         String filename=zbhList.stream().findFirst().get().getZbmc();
         try
         {
           HSSFWorkbook wb = new HSSFWorkbook();
           short rowHeight = 350;
           short sheet1CurrRow = 0;
           HSSFSheet sheet1 = wb.createSheet();
           for(int i=0; i<zbhList.size(); i++) { 
       		TSrhsDwcx zbhData =zbhList.get(i);
				if (zbhData.getSfxs()==1L){
					sheet1.setColumnWidth((short)i, (short)3000);
				} 	 
			}
           HSSFFooter footer = sheet1.getFooter();
           HSSFPrintSetup ps = sheet1.getPrintSetup();
           footer.setRight(HSSFFooter.page() + "/" + HSSFFooter.numPages());
           wb.setSheetName(0, filename);

           sheet1.setHorizontallyCenter(true);
           ps.setPaperSize((short)9);

           HSSFCellStyle btStyle = POIUtil.creatStyle(wb, (short)2, "宋体", 14, true, false);
           HSSFCellStyle centerTextStyle = POIUtil.creatStyle(wb, (short)2, "宋体", 10, false, true);
           HSSFCellStyle textStyle = POIUtil.creatStyle(wb, (short)1, "宋体", 9, false, true);
           HSSFCellStyle leftTextStyle = POIUtil.creatStyle(wb, (short)1, "宋体", 9, false, false);
           HSSFCellStyle rightTextStyle = POIUtil.creatStyle(wb, (short)3, "宋体", 9, false, false);
           textStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("text"));
           centerTextStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("text"));
           leftTextStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("text"));
           rightTextStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("text"));
           HSSFDataFormat df = wb.createDataFormat();
           HSSFCellStyle numericStyle = POIUtil.creatStyle(wb, (short)3, "宋体", 9, false, true);
           numericStyle.setDataFormat(df.getFormat("#,##0.00_);[Red]#,##0.00"));
        
            int cols=0;
        	for(int i=0; i<zbhList.size(); i++) { 
        		TSrhsDwcx zbhData =zbhList.get(i);
				if (zbhData.getSfxs()==1L){
					cols=cols+1;
				}	 
			}
        	int totalCols=cols+2;
        	POIUtil.setCellValue(sheet1, sheet1CurrRow, (short)0, filename, btStyle);
            sheet1.getRow(sheet1CurrRow).setHeight((short)600);
            sheet1.addMergedRegion(new CellRangeAddress(sheet1CurrRow, (short)0, sheet1CurrRow, (short)totalCols));
            sheet1CurrRow = (short)(sheet1CurrRow + 1);
            POIUtil.setCellValue(sheet1, sheet1CurrRow, (short)0, "单位编码", centerTextStyle);
            POIUtil.setCellValue(sheet1, sheet1CurrRow, (short)1, "单位名称", centerTextStyle);
        	for(int i=0; i<zbhList.size(); i++) { 
        		TSrhsDwcx zbhData =zbhList.get(i);
				if (zbhData.getSfxs()==1L){
					 POIUtil.setCellValue(sheet1, sheet1CurrRow, (short)(i+2), zbhData.getXsmc(), centerTextStyle);
				} 	 
			}
        	 sheet1.getRow(sheet1CurrRow).setHeight(rowHeight);
             sheet1CurrRow = (short)(sheet1CurrRow + 1);
          
             for (int i = 0; i < list.size(); i++) {
            	 ChangeHorizontal   cc= list.get(i);
            	 POIUtil.setCellValue(sheet1, sheet1CurrRow, (short)0, cc.getDwbm(), numericStyle);
            	 POIUtil.setCellValue(sheet1, sheet1CurrRow, (short)1, cc.getDwmc(), numericStyle);
            	 Map<String, BigDecimal> vmap=cc.getMap();
            	 int col=0;
            	 for (Map.Entry<String, BigDecimal> m : vmap.entrySet()) {
                     POIUtil.setCellValue(sheet1, sheet1CurrRow, (short)(col+2), m.getValue(), numericStyle);
                     col++;
            	 }
                 sheet1.getRow(sheet1CurrRow).setHeight(rowHeight);
                 sheet1CurrRow = (short)(sheet1CurrRow + 1); 
           }
           filename=IdUtils.fastSimpleUUID() +"_"+System.currentTimeMillis()+".xls";
           String filePath = SysConfig.getDownloadPath() + filename;
           File file = new File(filePath);
           wb.write(file);
           wb.close();
           ajax.success();
           ajax.put("filename", filename);
           /*
           String realFileName = System.currentTimeMillis() + filename.substring(filename.indexOf("_") + 1);
           response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
           FileUtils.setAttachmentResponseHeader(response, realFileName);
           FileUtils.writeBytes(filePath, response.getOutputStream());*/
         } catch (Exception e) {
        	  ajax.error(e.getMessage());
              e.printStackTrace();
         }
         return ajax;
    }
}
